package susebs.pb.travel_server.utils.DataInit;

import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import susebs.pb.travel_server.dao.HotelsDao;
import susebs.pb.travel_server.entity.Hotels;

import java.util.Iterator;

/**
 * 酒店信息初始化，用于填充酒店数据库
 */
@Component
public class HotelsData {

    private static HotelsDao dao;

//    初始化dao
    @Autowired
    public void setDao(HotelsDao dao){
        HotelsData.dao = dao;
    }

    /**
     *
     * @param addr 检索到的数据
     */
    public static void hotelDataInit(JsonNode addr){
        Hotels hotel;
        Iterator<JsonNode> elements = addr.get("results").elements();
        JsonNode node;

        while(elements.hasNext()){
            node = elements.next();
            hotel = new Hotels();

            hotel.setHotelName(node.get("name").asText());
            hotel.setHotelPrice("101元起");
            hotel.setHotelLng(node.get("location").get("lng").asDouble());
            hotel.setHotelLat(node.get("location").get("lat").asDouble());
            hotel.setHotelAddr(node.get("address").asText());
            hotel.setProvince(node.get("province").asText());
            hotel.setCity(node.get("city").asText());
            hotel.setArea(node.get("area").asText());

//            可能出现空值属性的处理
            String telephone = node.get("telephone") != null ? node.get("telephone").asText() : "未知电话";
            String label = node.get("detail_info").get("label") != null
                    ? node.get("detail_info").get("label").asText() : "暂未定级";
            Double overallRating = node.get("detail_info").get("overall_rating") != null
                    ? node.get("detail_info").get("overall_rating").asDouble() : 0.00;

            hotel.setHotelTelephone(telephone);
            hotel.setHotelLabel(label);
            hotel.setOverallRating(overallRating);

//            System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
//            System.out.println(hotel);
//            System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

            if(dao != null){
                dao.insert(hotel);
            }else{
                System.out.println("dao为空");
            }
        }
    }

}
